﻿using System.ComponentModel.DataAnnotations;
using System.Windows.Controls;
using System.Windows.Input;
using AIPASoft.CommonLibrary.WPF.MVVM.ViewModel;
using LoginManagerLibrary.Interfaces;

namespace LoginManagerLibrary
{
    internal class LoginViewModel : ValidationViewModel
    {
        private readonly IUserLogin _iUserLogin;

        #region Constructor

        public LoginViewModel(IUserLogin iUserLogin)
        {
            _iUserLogin = iUserLogin;
            Initialize();
        }

        private void Initialize()
        {
            _loginCommand = new RelayCommand(OnLoginButtonClick);
        }

        #endregion

        private string _userName = string.Empty;

        [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Err_Val_UserName")]
        public string UserName
        {
            get { return _userName; }
            set { _userName = value; OnPropertyChanged(); }
        }

        #region Login Command Implementation
        private ICommand _loginCommand;
        public ICommand LoginCommand
        {
            get { return _loginCommand; }
            set { _loginCommand = value; }
        }

        private void OnLoginButtonClick(object parameter)
        {
            var passwordBox = parameter as PasswordBox;
            if (passwordBox == null)
            {
                return;
            }
            string password = passwordBox.Password;
            string errorMessage = string.Empty;
            if (CanExecuteLoginCommand(password))
            {
               if(!_iUserLogin.Login(UserName, password,out errorMessage))
               {
                   //TODO: Update UI with validation Error.
               }
            }
        }

        private bool CanExecuteLoginCommand(string password)
        {
            //No Validation Error            //Password should not be empty or null
            var result = string.IsNullOrEmpty(Error) && !string.IsNullOrEmpty(password);
            return result;
        }

        #endregion
    }
}
